/**
 * 导出功能 Hook
 */

import { useCallback, useState } from 'react';
import { useProofMapper } from '@/contexts/ProofMapper';
import { showMessage } from '@/components/common/MessageTip';
// import { proofMapperAPI } from '@/api/proofMapper';
import type { ExportConfig, ExportFormat } from '@/types/ProofMapper';

export const useExport = () => {
  const {
    exportConfig,
    sortedItems,
    selectedItemsCount,
    setExportConfig,
    setLoading
  } = useProofMapper();

  const [exporting, setExporting] = useState(false);

  const exportData = useCallback(async (configParam?: ExportConfig) => {
    const finalExportConfig = configParam || exportConfig;
    
    const itemsToExport = finalExportConfig.selected_items_only 
      ? sortedItems.filter(item => item.selected)
      : sortedItems;

    if (itemsToExport.length === 0) {
      showMessage('warning', '没有可导出的项目');
      return;
    }

    setExporting(true);
    setLoading(true);

    try {
      // 调用真实的导出API（目前使用模拟逻辑）
      // const response = await proofMapperAPI.exportEvaluationList(
      //   exportConfig,
      //   itemsToExport.map(item => item.id)
      // );

      // 模拟导出过程
      await new Promise(resolve => setTimeout(resolve, 2000));

      // 模拟生成下载链接
      const filename = `安全评估证明材料清单_${new Date().toLocaleDateString()}.${finalExportConfig.format}`;
      
      showMessage('success', `导出成功！共导出 ${itemsToExport.length} 个项目`);
      
      // 这里应该触发实际的文件下载
      console.log('Export config:', finalExportConfig);
      console.log('Items to export:', itemsToExport);

      // 模拟文件下载
      const blob = new Blob([JSON.stringify(itemsToExport, null, 2)], {
        type: 'application/json'
      });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = filename;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);

    } catch (error) {
      showMessage('error', '导出失败，请重试');
      console.error('Export error:', error);
    } finally {
      setExporting(false);
      setLoading(false);
    }
  }, [exportConfig, sortedItems, setLoading]);

  const updateConfig = useCallback((key: keyof ExportConfig, value: any) => {
    setExportConfig({
      ...exportConfig,
      [key]: value
    });
  }, [exportConfig, setExportConfig]);

  const getExportItemsCount = useCallback(() => {
    return exportConfig.selected_items_only 
      ? selectedItemsCount 
      : sortedItems.length;
  }, [exportConfig.selected_items_only, selectedItemsCount, sortedItems.length]);

  const getExportModulesCount = useCallback(() => {
    const items = exportConfig.selected_items_only
      ? sortedItems.filter(item => item.selected)
      : sortedItems;
    return new Set(items.map(item => item.module)).size;
  }, [exportConfig.selected_items_only, sortedItems]);

  const getFormatDescription = useCallback((format: ExportFormat) => {
    const descriptions = {
      word: {
        title: 'Word 文档',
        subtitle: '格式化表格文档',
        description: '适合文档归档和正式提交'
      },
      excel: {
        title: 'Excel 表格',
        subtitle: '可编辑电子表格',
        description: '便于后续编辑和数据处理'
      }
    };
    return descriptions[format];
  }, []);

  return {
    exportData,
    exporting,
    config: exportConfig,
    updateConfig,
    exportItemsCount: getExportItemsCount(),
    exportModulesCount: getExportModulesCount(),
    getFormatDescription
  };
};
